<?php
namespace Api\Model;
use Common\helpers\Sms;
use Think\Model;
class SysCodeModel extends Model {
    protected $tableName = 'syscode';

    /***
     * 验证验证码是否过期
     * @param $number
     * @param $code
     */
    public static function checkCode($number,$code){
        $sysCode=new SysCodeModel();
        $result=$sysCode->where("is_use=0 AND send_type=0 AND number='$number' AND code='$code'")->find();
        if(!empty($result) && $result['expire_time']>time()){
            return true;
        }else{
            return false;
        }
    }


    /***
     * 删除验证码
     * @param $number
     * @param $code
     */
    public static function deleteCode($number,$code){
        $sysCode=new SysCodeModel();
        if($sysCode->where("is_use=0 AND send_type=0 AND number='$number'")->delete()){
            return true;
        }else{
            return false;
        }
    }

    /***
     * 获取验证码数据
     * @param $number
     * @param $code
     */
    public static function getCode($number){
        $sysCode=new SysCodeModel();
        $model=$sysCode->where("is_use=0 AND send_type=0 AND number='$number'")->order("id desc")->find();
        if(!empty($model)){
            return $model['created_time'];
        }else{
            return false;
        }
    }

    /***
     * 短信验证码发送
     * @param $number  手机号
     * @param $type  类型  0 注册 1是找回密码
     */
    public static function send($number,$type){
        $sysCode=new SysCodeModel();
        $time=time();
        $code=rand(100000,999999);
        $result=$sysCode->add([
            'number'=>$number,
            'code'=>$code,
            'is_use'=>0,
            'send_type'=>0,
            'expire_time'=>$time+(C("sendCodeExpTime")*60),
            'created_time'=>$time
        ]);
        if($result){
            
            //type 为0表示注册
            if($type==0){
				$temp_code="SMS_113445110";
                Sms::sendSms($number,$temp_code,"{\"code\":\"$code\"}");
                return true;
			//1是登录	
            }elseif($type==1){
				$temp_code="SMS_115750088";
				Sms::sendSms($number,$temp_code,"{\"code\":\"$code\"}");
                return true;
                //2找回密码
            }elseif($type==2){
                $temp_code="SMS_116591370";
                Sms::sendSms($number,$temp_code,"{\"code\":\"$code\"}");
                return true;
            }else{
				return false;
			}
        }else{
            return false;
        }
    }
}